﻿using Entity;
using Microsoft.AspNetCore.Http;
using ServiceCore;
using ServiceCore.Tool.NPOI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using ServiceCore.Tool;
using System.Web;
using System.IO;
using System.Data;

namespace Customer.Bussiness_Service
{

    public interface Iquestion_service
    {
        #region 题库 
        /// <summary>
        /// 添加/编辑
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultObjModel save(save_question Params);

        /// <summary>
        /// 获取补货详情分页列表
        /// </summary>
        /// <param name="Params"></param>
        /// <returns></returns>
        ResultListModel<question_body_searchshow> get_question_pagelist(get_question_query query);
        /// <summary>
        /// 变更题库状态
        /// </summary>
        /// <param name="question_id"></param>
        /// <param name="question_state"></param>
        /// <returns></returns>
        ResultObjModel change_state(string question_id, question_state? question_state);
        /// <summary>
        /// 删除题库
        /// </summary>
        /// <param name="question_id"></param>
        /// <returns></returns>
        ResultObjModel del(string question_id);
        /// <summary>
        ///获取题目详情
        /// </summary>
        /// <param name="question_id"></param>
        /// <returns></returns>
        ResultObjModel get_question_model(string question_id);
        #endregion
        #region 答题人员
        /// <summary>
        /// 获取答题人员列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModelWithObj<question_user_search> get_question_user_pagelist(user_search query);
        /// <summary>
        /// 保存答题人员
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel save_question_user(question_user model);
        /// <summary>
        ///  设置答题用户可用/禁用状态
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="isuse"></param>
        /// <returns></returns>
        ResultModel set_question_use_state(string uid, bool? isuse);
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        ResultModel del_question_user(string uid);
        /// <summary>
        /// 导入模板下载
        /// </summary>
        void question_user_template_down();
        /// <summary>
        /// 批量导入员工
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        ResultObjModel upload_user(IFormFileCollection files);
        /// <summary>
        /// 导出用户数据
        /// </summary>
        /// <param name="query"></param>
        void question_user_down(user_search query);
        /// <summary>
        /// 设置每天每人答题次数
        /// </summary>
        /// <param name="set_count"></param>
        /// <returns></returns>
        ResultObjModel set_baseuser_answer_count(int? set_count);
        #endregion 
        #region 答题策略
        /// <summary>
        /// 新增答题策略
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultModel save_question_strategy(save_question_strategy model);
        /// <summary>
        /// 获取答题策略列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        ResultListModel<question_strategy_for_search> get_question_strategy_pagelist(question_strategy_search query);
        /// <summary>
        /// 删除策略
        /// </summary>
        /// <param name="strategy_id"></param>
        /// <returns></returns>
        ResultModel del_question_strategy(string strategy_id);
        #endregion 
        #region 安卓答题
        /// <summary>
        /// 查询机器是否可用
        /// </summary>
        /// <param name="mchid"></param>
        /// <returns></returns>

        ResultObjModel check_mch_jurisdiction(string mchid);
        /// <summary>
        /// 获取机器列表
        /// </summary>
        /// <param name="mchid"></param>
        /// <returns></returns>
        ResultObjModel get_product_list(string mchid);
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="mchid"></param>
        /// <param name="worknum"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        ResultObjModel auth_login(string mchid, string worknum, string pwd);
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="mchid"></param>
        /// <param name="question_uid"></param>
        /// <param name="new_pwd"></param>
        /// <returns></returns>
        ResultObjModel set_new_pwd(string mchid, string question_uid, string new_pwd);
        /// <summary>
        /// 根据策略返回需要答题列表
        /// </summary>
        /// <param name="strategy_id"></param>
        /// <returns></returns>
        ResultObjModel get_question(string strategy_id);
        /// <summary>
        ///  提交答题结果
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        ResultObjModel submit_answer(submit_answer model);
        /// <summary>
        ///  确认出货完成
        /// </summary>
        /// <param name="order_id"></param>
        /// <param name="is_end"></param>
        /// <param name="out_params"></param>
        /// <returns></returns>
        ResultObjModel confirm_question_order(string order_id, bool? is_end, string out_params);
        #endregion
        #region 领取记录列表
        ResultListModel<quertion_order_search_item> get_question_order_pagelist(quertion_order_query query);
        #endregion
    }
    public class question_service : Iquestion_service
    {
        private readonly IToole_DI _tool;
        private readonly INpoi_service _excelservice;
        private readonly IHttpContextAccessor _context;
        public question_service(IToole_DI Tool, INpoi_service Excelservice, IHttpContextAccessor Context)
        {
            _tool = Tool;
            _excelservice = Excelservice;
            _context = Context;
        }
        #region 题库 
        /// <summary>
        /// 添加/编辑题目
        /// </summary>
        /// <returns></returns>
        public ResultObjModel save(save_question Params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(Params.body.question_id))
                {
                    Params.body.question_id = "";
                }
                if (string.IsNullOrWhiteSpace(Params.body.question_content))
                {
                    result.code = 1;
                    result.msg = "题目内容不能为空";
                    return result;
                }
                if (!Params.body.question_type.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须选择题目类型";
                    return result;
                }
                if (!Params.body.option_length.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须选择选项数量";
                    return result;
                }
                if (!Params.body.question_state.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须选择题目状态";
                    return result;
                }
                if (Params.option == null || !Params.option.Any())
                {
                    result.code = 1;
                    result.msg = "必须设置选项";
                    return result;
                }
                if (Params.option.Where(s => s.sort == null).Any())
                {
                    result.code = 1;
                    result.msg = "选项编号参数异常";
                    return result;
                }
                if (Params.option.Where(s => s.is_true == null).Any())
                {
                    result.code = 1;
                    result.msg = "必须指定选项是否正确答案";
                    return result;
                }
                if (Params.option.Where(s => string.IsNullOrWhiteSpace(s.option_content)).Any())
                {
                    result.code = 1;
                    result.msg = "不能存在空选项";
                    return result;
                }
                if (Params.body.option_length != Params.option.Count())
                {
                    result.code = 1;
                    result.msg = "设置题目选项数与实际提交选项数不符";
                    return result;
                }
                var grouplist = Params.option.GroupBy(s => s.sort.Value).Select(s => new { s.Key, key_count = s.Count() });
                if (grouplist.Where(s => s.key_count > 1).Any())
                {
                    result.code = 1;
                    result.msg = "不能重复设置选项编号";
                    return result;
                }
                switch (Params.body.question_type)
                {
                    case question_type.单选:
                        if (Params.option.Where(s => s.is_true.Value).Count() != 1)
                        {
                            result.code = 1;
                            result.msg = "单选题应有一个答案";
                            return result;
                        }
                        break;
                    case question_type.多选:
                        if (Params.option.Where(s => s.is_true.Value).Count() < 2)
                        {
                            result.code = 1;
                            result.msg = "多选题至少有两个答案";
                            return result;
                        }
                        break;
                    default:
                        result.code = 1;
                        result.msg = "题型提交错误";
                        return result;
                }

                //验证完成 开始组装必要项
                Params.body.baseuserid = _tool.di_user.RK_USER.BaseUserId;
                Params.body.answer_value = string.Join(',', Params.option.Where(s => s.is_true.Value).OrderBy(s => s.sort.Value).Select(s => s.sort).ToArray());
                string error = "";
                if (string.IsNullOrWhiteSpace(Params.body.question_id))
                {
                    Params.body.question_id = _tool.di_getid.IGet_SnowFlake_Id;
                    //添加题目
                    foreach (var item in Params.option)
                    {
                        item.baseuserid = Params.body.baseuserid;
                        item.question_id = Params.body.question_id;
                        item.question_option_id = Params.body.question_id + "-" + item.sort;
                    }
                    int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int rows = 0;
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<question_body>(), Params.body, tran);
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<question_option>(), Params.option, tran);
                        return rows;
                    }, ref error);
                }
                else
                {
                    ///编辑题目
                    var question_body_update = _tool.di_db.Get_rk_List<question_body>("select top 1 * from question_body where question_id=@question_id", new { Params.body.question_id }).FirstOrDefault();
                    if (question_body_update == null)
                    {
                        result.code = 1;
                        result.msg = "待修改题目不存在";
                        return result;
                    }
                    foreach (var item in Params.option)
                    {
                        item.baseuserid = Params.body.baseuserid;
                        item.question_id = Params.body.question_id;
                        item.question_option_id = Params.body.question_id + "-" + item.sort;
                    }
                    int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int rows = 0;
                        rows += conn.Execute(_tool.di_db.UpdateBySqlstr<question_body>(new string[] { "question_content", "question_type", "option_length", "question_state", "answer_value" }, new string[] { "question_id=@question_id" }), Params.body, tran);
                        rows += conn.Execute("delete from question_option where question_id=@question_id", Params.option, tran);
                        rows += conn.Execute(_tool.di_db.AddBySqlStr<question_option>(), Params.option, tran);
                        return rows;
                    }, ref error);
                }
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "保存成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "保存失败=>" + error;
                }
                return result;
            });
        }

        /// <summary>
        /// 获取补货详情分页列表
        /// </summary>
        /// <returns></returns>
        public ResultListModel<question_body_searchshow> get_question_pagelist(get_question_query query)
        {
            return CoreStartDo.ResultAction<ResultListModel<question_body_searchshow>>(result =>
            {
                string sql = "select * from question_body";
                string where = " where baseuserid=@baseuserid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.baseuserid = _tool.di_user.RK_USER.BaseUserId;
                if (!string.IsNullOrWhiteSpace(query.content))
                {
                    where += " and  content like @content";
                    query_dy.content = $"%{query.content}%";
                }
                if (query.question_type.HasValue)
                {
                    where += " and  question_type=@question_type";
                    query_dy.question_type = query.question_type.Value;
                }
                ResultListModel<question_body_searchshow> result_pagelist = _tool.di_db.GetRKPageList<question_body_searchshow>(sql, where, "addtime", query_dy, query.IsPage, query.page, query.pagesize);
                return result_pagelist;
            });
        }

        /// <summary>
        /// 获取题目详情
        /// </summary>
        /// <param name="question_id"></param>
        /// <returns></returns>

        public ResultObjModel get_question_model(string question_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                var question = _tool.di_db.Get_rk_List<question_body>("select top 1 * from  question_body where question_id=@question_id", new { question_id }).FirstOrDefault();
                List<question_option> option = new List<question_option>();
                if (question != null)
                {
                    option = _tool.di_db.Get_rk_List<question_option>("select * from question_option  where question_id=@question_id order by sort asc", new { question_id }).ToList();
                }
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    question,
                    option = from o in option
                             select new
                             {
                                 o.is_true,
                                 o.option_content,
                                 o.sort
                             }
                };
                return result;
            });
        }
        /// <summary>
        /// 变更题库状态
        /// </summary>
        /// <returns></returns>
        public ResultObjModel change_state(string question_id, question_state? question_state)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(question_id))
                {
                    result.code = 1;
                    result.msg = "题目ID不能为空";
                    return result;
                }
                if (!question_state.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须选择变更后的状态";
                    return result;
                }
                int change_rows = _tool.di_db.do_rk_Execute("update question_body set question_state=@question_state where question_id=@question_id", new { question_id, question_state });
                if (change_rows > 0)
                {
                    result.code = 0;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "设置失败=>" + change_rows;
                }
                return result;
            });
        }

        /// <summary>
        /// 删除题目
        /// </summary>
        /// <returns></returns>
        public ResultObjModel del(string question_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(question_id))
                {
                    result.code = 1;
                    result.msg = "题目ID不能为空";
                    return result;
                }
                var question = _tool.di_db.Get_rk_List<question_body>("select top 1 * from question_body where question_id=@question_id", new { question_id });
                if (question == null)
                {
                    result.code = 1;
                    result.msg = "待删除题目不存在";
                    return result;
                }
                string error = "";
                int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                {
                    int rows = 0;
                    rows += conn.Execute("delete from question_body where question_id=@question_id", new { question_id }, tran);
                    rows += conn.Execute("delete from question_option where question_id=@question_id", new { question_id }, tran);
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "删除失败=>" + error;
                }
                return result;
            });
        }

        #endregion
        #region 答题人员
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModelWithObj<question_user_search> get_question_user_pagelist(user_search query)
        {
            return CoreStartDo.ResultAction<ResultListModelWithObj<question_user_search>>(result =>
            {

                string sql = "select * from question_user";
                string where = " where baseuserid=@baseuserid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.baseuserid = _tool.di_user.RK_USER.BaseUserId;

                if (query.searchtype.HasValue && !string.IsNullOrWhiteSpace(query.searchkey))
                {
                    switch (query.searchtype.Value)
                    {

                        case user_search_type.编号:
                            where += "  and work_num like @work_num";
                            query_dy.work_num = $"%{ query.searchkey}%";
                            break;
                        case user_search_type.姓名:
                            where += "  and u_name like @u_name";
                            query_dy.u_name = $"%{ query.searchkey}%";
                            break;
                    }
                }
                if (query.isuse.HasValue)
                {
                    where += "  and isuse=@isuse";
                    query_dy.isuse = query.isuse;
                }
                ResultListModel<question_user_search> result_list = _tool.di_db.GetRKPageList<question_user_search>(sql, where, "question_uid", query_dy, query.IsPage, query.page, query.pagesize);
                result.code = result_list.code;
                result.msg = result_list.msg;
                result.rows = result_list.rows;
                result.current = result_list.current;
                var user_ext_params = _tool.di_db.Get_rk_List<string>("select ext_params from [user] where Id=@Baseuserid", new { Baseuserid = _tool.di_user.RK_USER.BaseUserId }).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(user_ext_params))
                {
                    result.exp = Newtonsoft.Json.JsonConvert.DeserializeObject<answer_count>(user_ext_params);
                }
                return result;
            });
        }
        /// <summary>
        /// 保存用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel save_question_user(question_user model)
        {
            ResultModel result = new ResultModel();
            try
            {
                #region  基础验证 
                if (string.IsNullOrWhiteSpace(model.question_uid))
                {
                    model.question_uid = "";
                }
                if (string.IsNullOrWhiteSpace(model.work_num))
                {
                    result.code = 1;
                    result.msg = "工号/账号不能为空";
                    return result;
                }
                else
                {
                    model.login_name = model.work_num;
                }
                var ExistModel = _tool.di_db.GetRKModel<question_user>(new string[] { "login_name=@login_name", "question_uid<>@question_uid" }, new { model.login_name, model.question_uid });
                if (ExistModel != null)
                {
                    result.code = 1;
                    result.msg = "账号已存在";
                    return result;
                }
                #endregion
                #region 数据处理 
                if (string.IsNullOrWhiteSpace(model.question_uid))
                {
                    if (string.IsNullOrWhiteSpace(model.login_pwd))
                    {
                        result.code = 1;
                        result.msg = "必须设置密码";
                        return result;
                    }
                    string savePwd = SecurityToMd5.Start(model.login_pwd + "^_^");
                    model.login_pwd = savePwd;
                    //添加
                    model.question_uid = _tool.di_getid.IGet_SnowFlake_Id;
                    model.addtime = DateTime.Now;
                    model.baseuserid = _tool.di_user.RK_USER.BaseUserId;
                    string error = "";
                    int resultCount = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int tranrow = 0;
                        tranrow += conn.Execute(_tool.di_db.AddBySqlStr<question_user>(), model, tran);
                        return tranrow;
                    }, ref error);
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "添加成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败 DB error=>" + error;
                    }
                }
                else
                {
                    //编辑
                    var needupdate = _tool.di_db.GetRKModel<question_user>(new string[] { "question_uid=@question_uid" }, new { model.question_uid });
                    if (needupdate == null)
                    {
                        result.code = 1;
                        result.msg = "修改信息不存在";
                        return result;
                    }

                    if (!string.IsNullOrWhiteSpace(model.login_pwd))
                    {
                        //当前修改了密码
                        string savePwd = SecurityToMd5.Start(model.login_pwd + "^_^");
                        model.login_pwd = savePwd;
                    }
                    else
                    {
                        model.login_pwd = needupdate.login_pwd;
                    }
                    model.login_name = model.work_num;
                    string error = "";
                    int resultCount = _tool.di_db.StartRKTran((conn, tran) =>
                    {
                        int tranrow = 0;
                        tranrow += conn.Execute(_tool.di_db.UpdateBySqlstr<question_user>(new string[] { "login_name", "u_name", "login_pwd", "link_phone", "remark", "work_num", "isuse" }, new string[] { "question_uid=@question_uid" }), model, tran);
                        return tranrow;
                    }, ref error);
                    if (resultCount > 0)
                    {
                        result.code = 0;
                        result.msg = "修改成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "修改成功 DB error";
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                result.code = 1;
                result.msg = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 设置用户可用状态
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public ResultModel set_question_use_state(string uid, bool? isuse)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {

                if (string.IsNullOrWhiteSpace(uid))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                if (!isuse.HasValue)
                {
                    result.code = 1;
                    result.msg = "请设置可用状态";
                }
                var user = _tool.di_db.Get_rk_List<question_user>("select top 1 * from question_user where question_uid=@uid", new { uid }).FirstOrDefault();
                if (user == null)
                {
                    result.code = 1;
                    result.msg = "用户不存在";
                    return result;
                }
                if (_tool.di_user.RK_USER.BaseUserId != user.baseuserid)
                {
                    result.code = 1;
                    result.msg = "您没有修改该用户权限";
                    return result;
                }
                //开始更新
                int update_row = _tool.di_db.do_rk_Execute("update question_user set isuse=@isuse where question_uid=@uid", new
                {
                    uid,
                    isuse = isuse.Value
                });
                if (update_row > 0)
                {
                    result.code = 0;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "设置成功";
                }
                return result;
            });
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public ResultModel del_question_user(string uid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(uid))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                var user = _tool.di_db.Get_rk_List<question_user>("select top 1 * from question_user where question_uid=@uid", new { uid }).FirstOrDefault();
                if (user == null)
                {
                    result.code = 1;
                    result.msg = "用户不存在";
                    return result;
                }
                if (_tool.di_user.RK_USER.BaseUserId != user.baseuserid)
                {
                    result.code = 1;
                    result.msg = "您没有删除该用户权限";
                    return result;
                }
                //开始删除数据
                int del_row = _tool.di_db.do_rk_Execute("delete from question_user where question_uid=@uid", new { uid });
                if (del_row > 0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败";
                }
                return result;
            });
        }
        /// <summary>
        /// 表格模板下载
        /// </summary>
        /// <returns></returns>
        public void question_user_template_down()
        {
            string title = $"{DateTime.Now.ToString("yyyy-MM-dd")}_答题用户上传模板.xlsx";
            List<string> titlelist = new List<string>() { "员工编号", "员工姓名", "可用(是/否)", "密码", "备注" };
            _excelservice.ExcelExport_Template(titlelist, dosomething: fs =>
            {
                _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
                _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
                int bufferSize = Convert.ToInt32(fs.Length);
                byte[] buffer;
                buffer = new byte[bufferSize];
                int currentRead = fs.Read(buffer, 0, bufferSize);
                _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
                _context.HttpContext.Response.Body.Flush();
            });
        }

        /// <summary>
        ///  导入答题用户
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public ResultObjModel upload_user(IFormFileCollection files)
        {
            return CoreStartDo.ResultAction(result =>
            {
                //if (_tool.di_user.USER == null)
                //{
                //    result.code = 1;
                //    result.msg = "who the fuck are you?";
                //    return result;
                //}
                long size = files.Sum(f => f.Length);
                if (files.Count <= 0)
                {
                    result.code = 1;
                    result.msg = "未检测到任何文件";
                    return result;
                }
                if (files.Count > 1)
                {
                    result.code = 1;
                    result.msg = "一次只能上传一个文件";
                    return result;
                }
                var excel = files.FirstOrDefault();
                string ext = Path.GetExtension(excel.FileName);
                const string fileFilt = ".xlsx|.xls";
                //判断后缀是否是图片
                if (ext == null)
                {
                    result.code = 1;
                    result.msg = "上传失败=>上传文件没有后缀名";
                    return result;
                }
                if (fileFilt.IndexOf(ext.ToLower(), StringComparison.Ordinal) <= -1)
                {
                    result.code = 1;
                    result.msg = "上传失败=>上传文件格式与下载模板不符";
                    return result;
                }
                Stream excel_stream = excel.OpenReadStream();
                DataTable DT = _excelservice.ReadExcelToDataTable(excel_stream, "Sheet1", true);
                List<question_user> new_user = new List<question_user>();
                string error = "";
                int error_count = 0;
                int row = 1;
                foreach (DataRow item in DT.Rows)
                {

                    question_user new_add_user = new question_user()
                    {
                        question_uid = _tool.di_getid.IGet_SnowFlake_Id,
                        addtime = DateTime.Now,
                        baseuserid = _tool.di_user.RK_USER.BaseUserId,
                        isuse = true
                    };
                    new_add_user.login_name = new_add_user.work_num = item["员工编号"].ToString();
                    if (string.IsNullOrWhiteSpace(new_add_user.login_name))
                    {
                        error += $"第{row}行员工编号存在空值,";
                        error_count++;
                        row++;
                        continue;
                    }
                    if (new_user.Where(s => s.login_name == new_add_user.login_name).Any())
                    {
                        error += $"第{row}行员工编号{new_add_user.login_name}存在重复数据已剔除未处理,";
                        error_count++;
                        row++;
                        continue;
                    }
                    new_add_user.u_name = item["员工姓名"].ToString();
                    new_add_user.remark = item["备注"].ToString();
                    new_add_user.isuse = item["可用(是/否)"].ToString() == "是" ? true : false;
                    var pwd = item["密码"].ToString();
                    if (string.IsNullOrWhiteSpace(pwd))
                    {
                        new_add_user.login_pwd = SecurityToMd5.Start("123123" + "^_^");
                    }
                    else
                    {
                        new_add_user.login_pwd = SecurityToMd5.Start(pwd + "^_^");
                    }
                    var ExistModel = _tool.di_db.GetRKModel<question_user>(new string[] { "login_name=@login_name", "baseuserid=@baseuserid", "question_uid<>@question_uid" }, new_add_user);
                    if (ExistModel != null)
                    {
                        error += $"第{row}行 {new_add_user.u_name}账号的员工编号{new_add_user.login_name}已存在,";
                        error_count++;
                        row++;
                        continue;
                    }
                    new_user.Add(new_add_user);

                }
                int tranrow = 0;
                if (new_user.Any())
                {
                    tranrow = _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<question_user>(), new_user);
                    if (string.IsNullOrWhiteSpace(error))
                    {
                        result.code = 0;
                        result.msg = $"导入成功{tranrow}条数据";
                    }
                    else
                    {
                        result.code = 0;
                        result.msg = $"导入成功,但失败了{error_count}条=>{error.TrimEnd(',')}";
                    }
                }
                else
                {
                    result.code = 1;
                    result.msg = $"导入失败,没有项被添加=>{error.TrimEnd(',')}";
                }
                return result;
            });
        }

        /// <summary>
        /// 导出用户数据
        /// </summary>
        public void question_user_down(user_search query)
        {
            query.IsPage = false;
            var listresult = get_question_user_pagelist(query);
            string title = $"{DateTime.Now.ToString("yyyy-MM-dd")}_{_tool.di_user.RK_USER.Id}_导出用户数据.xlsx";
            _excelservice.ExcelExportService(title, listresult.rows, dosomething: fs =>
           {
               _context.HttpContext.Response.ContentType = "application/octet-stream;charset=UTF-8";
               _context.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(title, System.Text.Encoding.UTF8));
               int bufferSize = Convert.ToInt32(fs.Length);
               byte[] buffer;
               buffer = new byte[bufferSize];
               int currentRead = fs.Read(buffer, 0, bufferSize);
               _context.HttpContext.Response.Body.Write(buffer, 0, currentRead);
               _context.HttpContext.Response.Body.Flush();
           });
        }
        /// <summary>
        ///设置指定商户答题次数 记录在对应商户的额外参数内
        /// </summary>
        /// <returns></returns>
        public ResultObjModel set_baseuser_answer_count(int? set_count)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (!set_count.HasValue)
                {
                    result.code = 1;
                    result.msg = "设置次数不能为空";
                    return result;
                }
                if (set_count < 0)
                {
                    result.code = 1;
                    result.msg = "设置次数不得小于0";
                }
                int set = _tool.di_db.do_rk_Execute("update [user] set ext_params=@ext_params where Id=@id", new
                {
                    id = _tool.di_user.RK_USER.BaseUserId,
                    ext_params = Newtonsoft.Json.JsonConvert.SerializeObject(new answer_count()
                    {
                        count = set_count.Value
                    })
                });
                if (set > 0)
                {
                    result.code = 0;
                    result.msg = "设置成功";
                }
                else
                {
                    result.code = 0;
                    result.msg = "设置失败";
                }
                return result;
            });
        }
        #endregion
        #region 答题策略
        /// <summary>
        /// 新增答题策略
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultModel save_question_strategy(save_question_strategy model)
        {
            return CoreStartDo.ResultAction<ResultModel>(result =>
            {
              
                if (!model.set_question_count.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须设置题目数量";
                    return result;
                }
                if (!model.set_pass_count.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须设置正确数量";
                    return result;
                }
                if (model.set_pass_count > model.set_question_count)
                {
                    result.code = 1;
                    result.msg = "设置正确数量不得大于设置题目数量";
                    return result;
                }
                Product product = new Product();
                if (model.question_strategy_type == question_strategy_type.按商品)
                {
                    if (string.IsNullOrWhiteSpace(model.product_id))
                    {
                        result.code = 1;
                        result.msg = "必须选择一件商品";
                        return result;
                    }
                    product = _tool.di_db.Get_rk_List<Product>("select top 1 * from product where id=@product_id", new { model.product_id }).FirstOrDefault();
                    if (product == null)
                    {
                        result.code = 1;
                        result.msg = "商品不存在";
                        return result;
                    }
                }
                Mch setmch = new Mch();
                if (model.question_strategy_type == question_strategy_type.按机器)
                {
                    if (string.IsNullOrWhiteSpace(model.mch_id))
                    {
                        result.code = 1;
                        result.msg = "必须选择一台设备进行设置";
                        return result;
                    }
                    setmch = _tool.di_db.Get_rk_List<Mch>("select top 1 * from Mch where id=@mch_id", new { model.mch_id }).FirstOrDefault();
                    if (setmch == null)
                    {
                        result.code = 1;
                        result.msg = "机器不存在";
                        return result;
                    }
                    if (model.strategy_id == null)
                    {
                        model.strategy_id = "";
                    }
                    //检测机器是否已经设置过其他策略了
                    int check_mch_strategy = _tool.di_db.Get_rk_List<int>("select count(*) from question_strategy  where baseuserid=@baseuserid and mch_id=@mch_id and strategy_id<>@strategy_id", new { baseuserid = _tool.di_user.RK_USER.BaseUserId, mch_id = model.mch_id, model.strategy_id }).FirstOrDefault();
                    if (check_mch_strategy > 0)
                    {
                        result.code = 1;
                        result.msg = "当前机器已经设置过答题策略,无法新增策略";
                        return result;
                    } 
                } 
                int count = _tool.di_db.Get_rk_List<int>("select count(1) from question_strategy where baseuserid=@baseuserid and product_id=@product_id and strategy_id<>@strategy_id", new
                {
                    baseuserid = _tool.di_user.RK_USER.BaseUserId,
                    product_id = model.product_id,
                    strategy_id = string.IsNullOrWhiteSpace(model.strategy_id) ? "" : model.strategy_id
                }).FirstOrDefault();
                if (count > 0)
                {
                    result.code = 1;
                    result.msg = "当前商品已设置";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.strategy_id))
                {
                    question_strategy new_mod = new question_strategy()
                    {
                        addtime = DateTime.Now,
                        product_id = product.Id,
                        product_name = product.Name,
                        product_pic = product.Img,
                        strategy_id = _tool.di_getid.IGet_SnowFlake_Id,
                        set_pass_count = model.set_pass_count.Value,
                        set_question_count = model.set_question_count.Value,
                        baseuserid = _tool.di_user.RK_USER.BaseUserId,
                        mch_id = setmch.Id,
                        strategy_type = model.question_strategy_type
                    };
                    int rows = _tool.di_db.do_rk_Execute(_tool.di_db.AddBySqlStr<question_strategy>(), new_mod);
                    if (rows > 0)
                    {
                        result.code = 0;
                        result.msg = "添加成功";
                        return result;
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败";
                        return result;
                    }
                }
                else
                {
                    var update_strategy = _tool.di_db.Get_rk_List<question_strategy>("select top 1 * from question_strategy where strategy_id=@strategy_id", new { model.strategy_id }).FirstOrDefault();
                    if (update_strategy == null)
                    {
                        result.code = 1;
                        result.msg = "待修改策略不存在";
                        return result;
                    }
                    update_strategy.product_id = product.Id;
                    update_strategy.product_name = product.Name;
                    update_strategy.product_pic = product.Img;
                    update_strategy.set_pass_count = model.set_pass_count.Value;
                    update_strategy.set_question_count = model.set_question_count.Value;
                    update_strategy.mch_id = setmch.Id;
                    update_strategy.strategy_type = model.question_strategy_type;
                    int rows = _tool.di_db.do_rk_Execute(_tool.di_db.UpdateBySqlstr<question_strategy>(new string[] { "product_id", "product_name", "product_pic", "set_pass_count", "set_question_count", "mch_id" , "strategy_type" }, new string[] { "strategy_id=@strategy_id" }), update_strategy);
                    if (rows > 0)
                    {
                        result.code = 0;
                        result.msg = "修改成功";
                    }
                    else
                    {
                        result.code = 1;
                        result.msg = "添加失败";
                    }
                }
                return result;
            });
        }
        /// <summary>
        /// 获取答题策略列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<question_strategy_for_search> get_question_strategy_pagelist(question_strategy_search query)
        {
            return CoreStartDo.ResultAction<ResultListModel<question_strategy_for_search>>(result =>
            {
                string sql = "select a.*,b.name as mch_name from question_strategy a left join mch b on a.mch_id=b.Id";
                string where = " where a.baseuserid=@baseuserid and a.strategy_type=@question_strategy_type";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.baseuserid = _tool.di_user.RK_USER.BaseUserId;
                query_dy.question_strategy_type = query.question_strategy_type;
                if (!string.IsNullOrWhiteSpace(query.product_name))
                {
                    where += "  and a.product_name like @product_name";
                    query_dy.product_name = $"%{ query.product_name}%";
                }
                if (query.set_question_count.HasValue)
                {
                    where += "  and a.set_question_count=@set_question_count";
                    query_dy.set_question_count = query.set_question_count;
                }
                if (!string.IsNullOrWhiteSpace(query.mch_name))
                {
                    where += "  and b.Name like @mch_name";
                    query_dy.mch_name = $"%{ query.mch_name}%";
                }
                result = _tool.di_db.GetRKPageList<question_strategy_for_search>(sql, where, "a.strategy_id", query_dy, query.IsPage, query.page, query.pagesize);
                return result;
            });
        }
        /// <summary>
        /// 删除策略
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public ResultModel del_question_strategy(string strategy_id)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(strategy_id))
                {
                    result.code = 1;
                    result.msg = "关键参数未入参";
                    return result;
                }
                var strategy = _tool.di_db.Get_rk_List<question_strategy>("select top 1 * from question_strategy where strategy_id=@strategy_id", new { strategy_id }).FirstOrDefault();
                if (strategy == null)
                {
                    result.code = 1;
                    result.msg = "策略不存在";
                    return result;
                }
                if (_tool.di_user.RK_USER.BaseUserId != strategy.baseuserid)
                {
                    result.code = 1;
                    result.msg = "您没有删除该用户权限";
                    return result;
                }
                //开始删除数据
                int del_row = _tool.di_db.do_rk_Execute("delete from question_strategy where strategy_id=@strategy_id", new { strategy_id });
                if (del_row > 0)
                {
                    result.code = 0;
                    result.msg = "删除成功";
                }
                else
                {
                    result.code = 1;
                    result.msg = "删除失败";
                }
                return result;
            });
        }
        #endregion 
        #region 安卓操作
        /// <summary>
        /// 检测机器答题权限
        /// </summary>
        /// <param name="mchid"></param>
        /// <returns></returns>
        public ResultObjModel check_mch_jurisdiction(string mchid) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID不能为空";
                    return result;
                }
                Mch mch = _tool.di_db.Get_rk_List<Mch>("select top 1 * from mch where Id=@mchid", new { mchid }).FirstOrDefault();
                if (mch == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                if (mch.State != MchState.可用)
                {
                    result.code = 1;
                    result.msg = "机器不可用";
                    return result;
                }
                //检测机器是否存在答题策略 
                var check_mch_strategy = _tool.di_db.Get_rk_List<question_strategy>("select * from question_strategy where baseuserid=@baseuserid and mch_id=@mch_id", new { baseuserid = mch.BaseUserId, mch_id = mchid }).FirstOrDefault();
                if (check_mch_strategy != null)
                {
                    result.code = 0;
                    result.msg = "设备可用";
                    result.data = new
                    {
                        check_mch_strategy.strategy_id,
                        check_mch_strategy.set_question_count, 
                        check_mch_strategy.set_pass_count
                    };
                    return result;
                }
                else
                {
                    result.code = 1;
                    result.msg = "该设备未设置任何答题规则";
                    return result;
                } 
            });
        }
        /// <summary>
        /// 获取商品列表
        /// </summary>
        /// <returns></returns>
        public ResultObjModel get_product_list(string mchid)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID不能为空";
                    return result;
                }
                Mch mch = _tool.di_db.Get_rk_List<Mch>("select top 1 * from mch where Id=@mchid", new { mchid }).FirstOrDefault();
                if (mch == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                if (mch.State != MchState.可用)
                {
                    result.code = 1;
                    result.msg = "机器不可用";
                    return result;
                }
                //开始加载数据信息
                string sql = "select a.*,b.slot_count from question_strategy a left join(select productid, sum(count) as slot_count from Slot where MchId=@mchid group by productid ) b on a.product_id = b.productid where a.baseuserid=@baseuserid";
                var resultlist = _tool.di_db.Get_rk_List<get_question_product_list>(sql, new { mchid, baseuserid = mch.BaseUserId });
                result.code = 0;
                result.msg = "success";
                result.data = from o in resultlist
                              select new
                              {
                                  o.strategy_id,
                                  o.product_name,
                                  o.product_pic,
                                  o.set_question_count,
                                  o.slot_count,
                                  o.set_pass_count
                              };
                return result;
            });
        } 
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="mchid"></param>
        /// <param name="worknum"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public ResultObjModel auth_login(string mchid, string worknum, string pwd)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID未上传";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(worknum) || string.IsNullOrWhiteSpace(pwd))
                {
                    result.code = 1;
                    result.msg = "用户编号或登录密码不能为空";
                    return result;
                }
                Mch mch = _tool.di_db.Get_rk_List<Mch>("select top 1 * from mch where Id=@mchid", new { mchid }).FirstOrDefault();
                if (mch == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                if (mch.State != MchState.可用)
                {
                    result.code = 1;
                    result.msg = "当前机器不可用";
                    return result;
                }
                User user = _tool.di_db.Get_rk_List<User>("select * from [user] where Id=@Id", new { Id = mch.BaseUserId }).FirstOrDefault();
                if (user == null)
                {
                    result.code = 1;
                    result.msg = "商户不存在";
                    return result;
                }
                question_user loguser = _tool.di_db.Get_rk_List<question_user>("select top 1 * from question_user where baseuserid=@baseuserid and work_num=@work_num", new { baseuserid = mch.BaseUserId, work_num = worknum }).FirstOrDefault();
                if (loguser == null)
                {
                    result.code = 1;
                    result.msg = "用户名或密码不正确";
                    return result;
                }
                if (!loguser.isuse)
                {
                    result.code = 1;
                    result.msg = "登录用户已禁用";
                    return result;
                }
                string check = SecurityToMd5.Start(pwd + "^_^");
                if (loguser.login_pwd != check)
                {
                    result.code = 1;
                    result.msg = "用户名或密码不正确";
                    return result;
                }
                int max_count = -1;
                try {
                    if (!string.IsNullOrWhiteSpace(user.ext_params))
                    {
                        max_count = Newtonsoft.Json.JsonConvert.DeserializeObject<answer_count>(user.ext_params).count;
                    }
                } catch { }
                if (max_count == 0)
                {
                    ///如果设置的最大答题数量为0 则不做限制 (后加判断)
                }
                else if (max_count == -1)
                {
                    result.code = 1;
                    result.msg = "当前商户未设置每日答题数量";
                    return result;
                }
                else
                {
                    int today_order = _tool.di_db.Get_rk_List<int>("select count(*) from question_order where baseuserid=@baseuserid and add_time>=@today_time and question_uid=@question_uid", new
                    {
                        baseuserid = mch.BaseUserId,
                        today_time = Convert.ToDateTime(DateTime.Now.ToLongDateString()),
                        question_uid = loguser.question_uid
                    }).FirstOrDefault();
                    if (today_order >= max_count)
                    {
                        result.code = 1;
                        result.msg = "您今日答题数量已达到上限,请明天再试";
                        return result;
                    }
                }
                result.code = 0;
                result.msg = "success";
                result.data = new
                {
                    loguser.question_uid
                };
                return result;
            });
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="question_uid"></param>
        /// <param name="new_pwd"></param>
        /// <returns></returns>
        public ResultObjModel set_new_pwd(string mchid, string question_uid, string new_pwd)
        {
            return CoreStartDo.ResultAction(result =>
            {

                if (string.IsNullOrWhiteSpace(mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID未上传";
                    return result;
                } 
                question_user loguser = _tool.di_db.Get_rk_List<question_user>("select top 1 * from question_user where question_uid=@question_uid", new { question_uid }).FirstOrDefault();
                if (loguser == null)
                {
                    result.code = 1;
                    result.msg = "用户不存在";
                    return result;
                }
                string set_pwd = SecurityToMd5.Start(new_pwd + "^_^");
                int update_row = _tool.di_db.do_rk_Execute("update question_user set login_pwd=@login_pwd where question_uid=@question_uid", new { question_uid, login_pwd = set_pwd });
                if (update_row > 0)
                {
                    result.code = 0;
                    result.msg = "修改成功"; 
                }
                else
                {
                    result.code = 0;
                    result.msg = "修改失败"; 
                } 
                return result;
            });
        }


        /// <summary>
        /// 根据策略生成题库
        /// </summary>
        /// <param name="strategy_id"></param>
        /// <returns></returns>
        public ResultObjModel get_question(string strategy_id) {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(strategy_id))
                {
                    result.code = 1;
                    result.msg = "策略信息未上传";
                    return result;
                }
                question_strategy strategy = _tool.di_db.Get_rk_List<question_strategy>("select top 1 * from question_strategy where strategy_id=@strategy_id", new { strategy_id }).FirstOrDefault();
                if (strategy == null)
                {
                    result.code = 1;
                    result.msg = "策略不存在";
                    return result;
                }
                int set_count = strategy.set_question_count;
                //获取应该答题数量
                List<return_question_item> question = new List<return_question_item>();
                int question_index = 1;
                while (set_count > 0)
                {
                    try {
                        string sql = $"select top {set_count} * from question_body where baseuserid=@baseuserid and question_state=1 order by NewID()";
                        var db_question = _tool.di_db.Get_rk_List<question_body>(sql, new { strategy.baseuserid, }).ToList();
                        foreach (var item in db_question)
                        {
                            question.Add(new return_question_item()
                            {
                                question_index = question_index,
                                question_id = item.question_id,
                                question_type = item.question_type.Value,
                                question_content = item.question_content
                            });
                            question_index++;
                            set_count--;
                            if (set_count == 0)
                            {
                                break;
                            }
                        } 
                    }
                    catch
                    {
                        set_count--;
                    } 
                } 
                var  select_arr = question.Select(s => s.question_id).Distinct();
                List<question_option> option_list = _tool.di_db.Get_rk_List<question_option>("select * from question_option where question_id in @question_ids", new { question_ids = select_arr.ToArray() }).ToList();
                foreach (var item in question)
                {
                    item.options = from o in option_list.Where(s => s.question_id == item.question_id).OrderBy(s => s.sort)
                                   select new return_question_option()
                                   {
                                       option_content = o.option_content,
                                       sort = o.sort.Value
                                   };
                }
                result.code = 0;
                result.msg = "success";
                result.data = question;
                return result;
            });
        }
        /// <summary>
        /// 提交答案
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultObjModel submit_answer(submit_answer model)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(model.mchid))
                {
                    result.code = 1;
                    result.msg = "机器ID不能为空";
                    return result;
                }
                if (string.IsNullOrWhiteSpace(model.strategy_id))
                {
                    result.code = 1;
                    result.msg = "所选商品不能为空";
                    return result;
                }  
                Mch mch = _tool.di_db.Get_rk_List<Mch>("select top 1 * from mch where Id=@mchid", new { model.mchid }).FirstOrDefault();
                if (mch == null)
                {
                    result.code = 1;
                    result.msg = "机器不存在";
                    return result;
                }
                if (mch.State != MchState.可用)
                {
                    result.code = 1;
                    result.msg = "机器不可用";
                    return result;
                }
                User user = _tool.di_db.Get_rk_List<User>("select * from [user] where Id=@Id", new { Id = mch.BaseUserId }).FirstOrDefault();
                if (user == null)
                {
                    result.code = 1;
                    result.msg = "商户不存在";
                    return result;
                }
                question_strategy strategy = _tool.di_db.Get_rk_List<question_strategy>("select top 1 * from question_strategy where strategy_id=@strategy_id", new { model.strategy_id }).FirstOrDefault();
                if (strategy == null)
                {
                    result.code = 1;
                    result.msg = "提交策略不存在";
                    return result;
                }
                question_user loguser = new question_user()
                {
                    question_uid = "0",
                    u_name = "no need",
                    work_num = "0"
                };
                if (model.need_check_user)
                {
                    if (string.IsNullOrWhiteSpace(model.question_uid))
                    {
                        result.code = 1;
                        result.msg = "答题人信息不能为空";
                        return result;
                    }
                    loguser = _tool.di_db.Get_rk_List<question_user>("select top 1 * from question_user where question_uid=@question_uid", new { question_uid = model.question_uid }).FirstOrDefault();
                    if (loguser == null)
                    {
                        result.code = 1;
                        result.msg = "用户名或密码不正确";
                        return result;
                    }
                    int max_count = -1;
                    try
                    {
                        if (!string.IsNullOrWhiteSpace(user.ext_params))
                        {
                            max_count = Newtonsoft.Json.JsonConvert.DeserializeObject<answer_count>(user.ext_params).count;
                        }
                    }
                    catch { }
                    //如果设置为0则不做限制
                    if (max_count == 0)
                    {
                        ///如果设置的最大答题数量为0 则不做限制 (后加判断)
                    }
                    else if (max_count == -1)
                    {
                        result.code = 1;
                        result.msg = "当前商户未设置每日答题数量";
                        return result;
                    }
                    else
                    {
                        int today_order = _tool.di_db.Get_rk_List<int>("select count(*) from question_order where baseuserid=@baseuserid and add_time>=@today_time and question_uid=@question_uid", new
                        {
                            baseuserid = mch.BaseUserId,
                            today_time = Convert.ToDateTime(DateTime.Now.ToLongDateString()),
                            question_uid = loguser.question_uid
                        }).FirstOrDefault();
                        if (today_order >= max_count)
                        {
                            result.code = 1;
                            result.msg = "您今日答题数量已达到上限,请明天再试";
                            return result;
                        }
                    }
                } 
                if (model.answer_list.Count != strategy.set_question_count)
                {
                    result.code = 1;
                    result.msg = "答题数与设置策略不符";
                    return result;
                }
                //准备创建答题订单
                question_order order = new question_order()
                {
                    add_time = DateTime.Now,
                    baseuserid = mch.BaseUserId,
                    mch_id = mch.Id,
                    mch_name = mch.Name,
                    mch_sn = mch.SN,
                    order_id = _tool.di_getid.IGet_SnowFlake_Id,
                    product_id = strategy.product_id,
                    product_name = strategy.product_name,
                    product_pic = strategy.product_pic,
                    question_uid = loguser.question_uid,
                    u_name = loguser.u_name,
                    set_pass_count = strategy.set_pass_count,
                    set_question_count = strategy.set_question_count,
                    strategy_id = strategy.strategy_id,
                    work_num = loguser.work_num,
                    is_end = false,
                    order_state = question_order_state.待处理,
                    strategy_type = strategy.strategy_type
                };
                //定义答题记录列表容器
                List<question_order_record> record_list = new List<question_order_record>();
                //获取题目列表
                List<question_body> in_stock_questions = _tool.di_db.Get_rk_List<question_body>("select * from question_body where question_id in @question_ids", new { question_ids = model.answer_list.Select(s => s.question_id).Distinct().ToArray() }).ToList();
                //定义正确答案选项id容器
                List<string> get_option_id = new List<string>();
                //开始判断题目是否正确
                foreach (var item in model.answer_list)
                {
                    var in_db_question = in_stock_questions.Where(s => s.question_id == item.question_id).FirstOrDefault();
                    if (in_db_question == null)
                    {
                        result.code = 1;
                        result.msg = $"题目{item.question_index}不存在或已经被删除";
                        return result;
                    }
                    foreach (var answer_value in in_db_question.answer_value.Split(','))
                    {
                        get_option_id.Add($"{in_db_question.question_id}-{answer_value}");
                    }
                    string submit_answer_sort = string.Join(',', item.submit_answer.OrderBy(s => s).ToArray()); 
                    question_order_record record_item = new question_order_record();
                    record_item.order_id = order.order_id;
                    record_item.order_record_id = _tool.di_getid.IGet_SnowFlake_Id;
                    record_item.question_content = in_db_question.question_content;
                    record_item.question_id = in_db_question.question_id;
                    record_item.question_sort = item.question_index;
                    record_item.set_answer = in_db_question.answer_value;
                    record_item.sub_answer = submit_answer_sort;
                    if (record_item.set_answer == record_item.sub_answer)
                    {
                        record_item.is_right = true;
                    }
                    else
                    {
                        record_item.is_right = false;
                    }
                    
                    record_list.Add(record_item);
                }
                List<question_option> in_stock_question_option = _tool.di_db.Get_rk_List<question_option>("select * from question_option where question_option_id in @options", new { options = get_option_id }).ToList();
                foreach (var item in record_list)
                {
                    var list = Array.ConvertAll(item.set_answer.Split(','), int.Parse).ToList();
                    var data = from o in in_stock_question_option.Where(s => s.question_id == item.question_id && list.Contains(s.sort.Value)).OrderBy(s => s.sort)
                               select new
                               {
                                   o.sort,
                                   o.option_content
                               };
                    item.answer_content = Newtonsoft.Json.JsonConvert.SerializeObject(data);
                }
                //处理一圈以后可以判断当前答题情况了
                if (record_list.Where(s => s.is_right).Count() >= strategy.set_pass_count)
                {
                    //实际答题正确数量大于等于设置策略正确题目数,可以出货
                    order.is_pass = true;
                }
                else
                {
                    order.is_pass = false;
                }
                var answer_details_obj = from o in record_list.OrderBy(s => s.question_sort)
                                         select new
                                         {
                                             o.question_id,
                                             o.question_content,
                                             question_index = o.question_sort,
                                             o.is_right,
                                             answer_content = Newtonsoft.Json.Linq.JArray.Parse(o.answer_content),
                                         }; 
                if (!order.is_pass)
                {
                    //不能出货,直接返回吧.
                    result.code = 0;
                    result.msg = "答题成功";
                    result.data = new
                    {
                        can_out = false, //是否可以出货
                        total_question = record_list.Count,
                        success_question = record_list.Where(s => s.is_right).Count(),
                        error_question = record_list.Where(s => !s.is_right).Count(),
                        details = answer_details_obj.ToList()
                    };
                    order.is_end = true;//题目都答错了 不会再出货了 直接标记订单结束
                    order.order_state = question_order_state.已完成;
                    ///填充答题正确数
                    order.submit_pass_count = record_list.Where(s => s.is_right).Count();
                }
                else
                {
                    Slot out_slot = null;
                    if (strategy.strategy_type == question_strategy_type.按商品)
                    {
                        //达到领取要求了,获取一下货道 准备出货
                        out_slot = _tool.di_db.Get_rk_List<Slot>("select top 1 * from slot where mchid=@mchid and productid=@product_id and count>0 and SlotStateId=@SlotStateId order by [index]", new
                        {
                            mchid = mch.Id,
                            product_id = strategy.product_id,
                            SlotStateId = SlotState.可用
                        }).FirstOrDefault();
                    }
                    else if (strategy.strategy_type == question_strategy_type.按机器)
                    {
                        //达到领取要求了,获取一下货道 准备出货
                        out_slot = _tool.di_db.Get_rk_List<Slot>("select top 1 * from slot where mchid=@mchid and count>0  and SlotStateId=@SlotStateId order by [index]", new
                        {
                            mchid = mch.Id,
                            product_id = strategy.product_id,
                            SlotStateId = SlotState.可用
                        }).FirstOrDefault();
                    }
                    if (out_slot == null)
                    {
                        result.code = 1;
                        result.msg = "库存不足";
                        return result;
                    }
                    else
                    {
                        ///持续填充订单数据
                        order.out_slot = out_slot.index;
                        order.remark = out_slot.index + "货道-" + out_slot.productname;
                    }
                    //可以出货
                    result.code = 0;
                    result.msg = "答题成功";
                    result.data = new
                    {
                        can_out = true, //是否可以出货
                        order.out_slot,
                        out_slot.SlotTypeId,
                        order.order_id,
                        total_question = record_list.Count,
                        success_question = record_list.Where(s => s.is_right).Count(),
                        error_question = record_list.Where(s => !s.is_right).Count(),
                        details = answer_details_obj.ToList() 
                    };
                    ///填充答题正确数
                    order.submit_pass_count = record_list.Where(s => s.is_right).Count();
                }
                ///数据处理阶段完成,开始储存数据
                string error = "";
                int tran_rows = _tool.di_db.StartRKTran((conn, tran) =>
                {
                    int rows = 0;
                    rows += conn.Execute(_tool.di_db.AddBySqlStr<question_order>(), order, tran);
                    rows += conn.Execute(_tool.di_db.AddBySqlStr<question_order_record>(), record_list, tran);
                    return rows;
                }, ref error);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    result.code = 1;
                    result.msg = $"储存数据异常{error}";
                } 
                return result;
            });
        }
        /// <summary>
        /// 确认订单完成情况
        /// </summary>
        /// <returns></returns>
        public ResultObjModel confirm_question_order(string order_id, bool? is_end, string out_params)
        {
            return CoreStartDo.ResultAction(result =>
            {
                if (string.IsNullOrWhiteSpace(order_id))
                {
                    result.code = 1;
                    result.msg = "订单ID不能为空";
                    return result;
                }
                if (!is_end.HasValue)
                {
                    result.code = 1;
                    result.msg = "必须标记订单是否出货完成";
                    return result;
                }
                question_order q_o = _tool.di_db.Get_rk_List<question_order>("select top 1 * from question_order where order_id=@order_id", new { order_id = order_id }).FirstOrDefault();
                if (q_o == null)
                {
                    result.code = 1;
                    result.msg = "订单不存在";
                    return result;
                }
                if (q_o.order_state == question_order_state.已完成)
                {
                    result.code = 1;
                    result.msg = "订单已处理";
                    return result;
                }
                string error = "";
                int tranrows = _tool.di_db.StartRKTran((conn, tran) => {
                    int rows = 0;
                    rows += conn.Execute("update question_order set is_end=@is_end,out_params=@out_params,order_state=@order_state where order_id=@order_id", new { is_end, out_params, order_id, order_state = question_order_state.已完成 }, tran);
                    if (is_end.Value)
                    {
                        //扣除库存
                        rows += conn.Execute("update slot set count=count-1 where Id=@slot_id and count>0", new { slot_id = $"{q_o.mch_id}-{q_o.out_slot}" }, tran);
                    } 
                    return rows;
                }, ref error);
                if (string.IsNullOrWhiteSpace(error))
                {
                    result.code = 0;
                    result.msg = "success";
                    result.data = new { tranrows };
                }
                else {
                    result.code = 1;
                    result.msg = "添加数据失败";
                    result.data = new { tranrows };
                }
                return result;
            });
        }
        #endregion
        #region 领取记录列表
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ResultListModel<quertion_order_search_item> get_question_order_pagelist(quertion_order_query query)
        {
            return CoreStartDo.ResultAction<ResultListModel<quertion_order_search_item>>(result =>
            {

                string sql = "select * from question_order";
                string where = " where baseuserid=@baseuserid";
                dynamic query_dy = new System.Dynamic.ExpandoObject();
                query_dy.baseuserid = _tool.di_user.RK_USER.BaseUserId; 
                if (query.searchtype.HasValue && !string.IsNullOrWhiteSpace(query.searchkey))
                {
                    switch (query.searchtype.Value)
                    {

                        case user_search_type.编号:
                            where += "  and work_num like @work_num";
                            query_dy.work_num = $"%{ query.searchkey}%";
                            break;
                        case user_search_type.姓名:
                            where += "  and u_name like @u_name";
                            query_dy.u_name = $"%{ query.searchkey}%";
                            break;
                    }
                }
                if (!string.IsNullOrWhiteSpace(query.mch_name))
                {
                    where += "  and mch_name like @mch_name";
                    query_dy.mch_name = $"%{ query.mch_name}%";
                }
                if (!string.IsNullOrWhiteSpace(query.product_name))
                {
                    where += "  and product_name like @product_name";
                    query_dy.product_name = $"%{ query.product_name}%";
                }

                if (query.is_pass.HasValue)
                {
                    where += "  and is_pass=@is_pass";
                    query_dy.is_pass = query.is_pass.Value;
                }
                DateTime sdt;
                if (!string.IsNullOrWhiteSpace(query.start_time))
                {
                    if (DateTime.TryParse(query.start_time, out sdt))
                    {
                        where += "  and add_time>=@sdt";
                        query_dy.sdt = sdt;
                    }
                }
                DateTime edt;
                if (!string.IsNullOrWhiteSpace(query.end_time))
                {
                    if (DateTime.TryParse(query.end_time, out edt))
                    {
                        where += "  and add_time<=@edt";
                        query_dy.edt = edt;
                    }
                } 
                ResultListModel<quertion_order_search_item> result_list = _tool.di_db.GetRKPageList<quertion_order_search_item>(sql, where, "order_id", query_dy, query.IsPage, query.page, query.pagesize);
                return result_list;
            });
        } 
        #endregion
    }
}
